class NotesController < ApplicationController
  before_filter :login_required, :authorization_required, :find_customer
  
  verify :method => :put, :only => [ :update ], :redirect_to => { :action => :index }
  verify :method => :post, :only => [ :create ], :redirect_to => { :action => :index }
  verify :method => :delete, :only => [ :destroy ], :redirect_to => { :action => :index }
  
  def index
    if @customer.nil?
      @notes = Note.find(:all, :order => 'created_on desc')
    else
      @notes = @customer.notes
    end
    respond_to do |format|
      format.html {render :action => 'list.html.erb'}
      format.js {render :action => 'list.js.rjs'}
      format.xml {render :xml => @notes.to_xml}
    end
  end
    
  def new
    @note = Note.new
    respond_to do |format|
      format.html {render :action => 'new.html.erb'}
      format.js {render :action => 'new.js.rjs'}
    end
  end
  
  def create
    note = Note.new(params[:note])
    @customer.notes << note
    @notes = @customer.notes
    if @customer.save
      if request.xhr?
        render :action => 'list.js.rjs'
      else
        redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
      end
    else
      render :action => 'new' unless request.xhr?
    end
  end
  
  def edit
    @note = Note.find(params[:id])
    respond_to do |format|
      format.html {render :action => 'edit.html.erb'}
      format.js {render :action => 'edit.js.rjs'}
    end
  end
  
  def update
    @note = Note.find(params[:id])
    @notes = @customer.notes
    if @note.update_attributes(params[:note])
      if request.xhr?
        render :action => 'list.js.rjs'
      else
        redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
      end
    else
      render :action => 'edit' unless request.xhr?
    end
  end
  
  def destroy_selected
    unless params[:selected].nil?
      note = Note.find(params[:selected])
      @customer = note.customer
      note.destroy
      @notes = @customer.notes
    end
    if request.xhr?
      render :action => 'list.js.rjs'
    else
      redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
    end
  end
end

